package com.imay.live.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.imay.base.adapter.SimpleFragmentPagerAdapter;
import com.imay.base.helper.ActivityHelper;
import com.imay.base.util.StringUtil;
import com.imay.cocos.IMayCocos;
import com.imay.cocos.IMayCocosNetManager;
import com.imay.live.Constants;
import com.imay.live.IMApplication;
import com.imay.live.R;
import com.imay.live.activity.dynamics.ReleaseActivity;
import com.imay.live.activity.load.WebCallBackActivity;
import com.imay.live.activity.family.FamilyParams;
import com.imay.live.activity.family.manager.FamilyManager;
import com.imay.live.activity.family.manager.FamilyUserChangeManager;
import com.imay.live.activity.recharge.RechargeActivity;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.cache.UserInfoCache;
import com.imay.live.fragment.MainActionButtonFragment;
import com.imay.live.fragment.NoticeFragment;
import com.imay.live.fragment.ProfileFragment;
import com.imay.live.fragment.discovery.DiscoveryFragment;
import com.imay.live.fragment.discovery.LoadFragment;
import com.imay.live.fragment.dynamics.DynamicsFragment;
import com.imay.live.fragment.room.RoomFloorGuideFragment;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.EventHelper;
import com.imay.live.helper.H5Helper;
import com.imay.live.helper.PreferenceHelper;
import com.imay.live.helper.RoomHouseHelper;
import com.imay.live.helper.ThreadManager;
import com.imay.live.helper.TitleBarClickHelper;
import com.imay.live.manager.AccountManager;
import com.imay.live.manager.AdManager;
import com.imay.live.manager.DataSetManager;
import com.imay.live.manager.DynamicsNotifyManager;
import com.imay.live.manager.FamilyAccountManager;
import com.imay.live.manager.FirstRechargeManager;
import com.imay.live.manager.MessageManager;
import com.imay.live.manager.NoticeBubbleManager;
import com.imay.live.manager.UnreadManager;
import com.imay.live.model.AdsModel;
import com.imay.live.model.NewMailModel;
import com.imay.live.model.SysConfigModel;
import com.imay.live.model.SysparamModel;
import com.imay.live.model.UnreadModel;
import com.imay.live.model.UserInfoModel;
import com.imay.live.params.IMParams;
import com.imay.live.proto.Result;
import com.imay.live.proto.family.FamilyApplyNotify;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.update.CheckUpdateApp;
import com.imay.live.utils.AppUtil;
import com.imay.live.utils.GlideUtil;
import com.imay.live.utils.ImayLogUtil;
import com.imay.live.utils.TimeUtil;
import com.imay.live.view.WebpView;
import com.imay.live.view.custom.NavigationTabView;
import com.imay.live.view.dialog.ShowAdsFragment;
import com.imay.live.view.indicator.Indicator;
import com.imay.tbas_api.IMYTBASObject;

import java.util.ArrayList;
import java.util.List;

import static com.imay.live.helper.UmengPushHelper.ENTER_USER_CALLLIVE;
import static com.imay.live.manager.AdManager.TYPE_DISCOVERY;
import static com.imay.live.manager.AdManager.TYPE_DYNAMICS;
import static com.imay.live.manager.AdManager.TYPE_OTHER;
import static com.imay.live.manager.AdManager.TYPE_PROFILE;
import static com.imay.live.manager.MessageManager.NewWarnType.IMBubbleCommentType;
import static com.imay.live.manager.MessageManager.NewWarnType.IMBubbleFollowType;
import static com.imay.live.manager.MessageManager.NewWarnType.IMBubbleGiftType;
import static com.imay.live.manager.MessageManager.NewWarnType.IMBubbleMindType;
import static com.imay.live.manager.MessageManager.NewWarnType.IMBubblePraiseType;
import static com.imay.live.manager.MessageManager.NewWarnType.IMBubbleRePostType;
import static com.imay.live.manager.UnreadManager.TYPE_UNREAD_CALL_LIVE_PROFILE;
import static com.imay.live.manager.UnreadManager.TYPE_UNREAD_FAMILY_MESSAGE;
import static com.imay.live.manager.UnreadManager.TYPE_UNREAD_MESSAGE;
import static com.imay.live.manager.UnreadManager.TYPE_UNREAD_SYSTEM_PROFILE;
import static com.imay.live.params.IMParams.CONFIG_SWITCH_RECHARGE_TIP;
import static com.imay.live.params.IMParams.CONFIG_VALUE_RECHARGE_TIP_URL2;
import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * Created by jeaman on 2017/2/15.
 */

public class MainActivity2 extends BaseUserActivity implements AppBarLayout.OnOffsetChangedListener, View.OnClickListener, ProtoCallBack, UnreadManager.ChangeUnreadStatusListener, DynamicsNotifyManager.DynamicNotifyListener, IMayCocosNetManager.OnCocosShopListener, AdManager.OnShowAdListener, FamilyManager.FamilyListener, FamilyUserChangeManager.FamilyUserChangeListener {
    private final static String BUNDLE_NAME_SELECT_TAB_ID = "SELECT_TAB_ID";
    private final static String EXTRA_NOTIFY_TYPE = "EXTRA_NOTIFY_TYPE";
    //TAB资源id
    private final static int TAB_TITLES[] = new int[]{R.string.str_bottom_faxian, R.string.str_bottom_dongtai, R.string.str_bottom_tongzhi, R.string.str_bottom_me};

    private DiscoveryFragment mDiscoveryFragment;
    private Handler dynamicsFragmentHandler;

    private int mSelectTabId;
    private long mPressBackTime = 0;
    private SparseArray<NavigationTabView> mTabButtonArray = new SparseArray<>();

    //标题栏滑动相关
    int tabH;
    private CheckUpdateApp checkUpdateApp;
    private RoomHouseHelper roomHouseHelper;//建楼卡
    private IMYTBASObject mSocketNotify;
    private boolean ispause;
    /**
     * ==========权限==========
     */
    private String loadSystemNoticeRedCommand;
    private String loadSysParamGameShowRequest;
    private NavigationTabView radiodynamics, radiodiscovery, radionotice, radiomine;
    private boolean isDynamicsRed = false;
    private boolean hasUnreadNotice;
    private boolean hasUnreadMessage, hasUnreadSystem;

    private NoticeFragment noticeFragment;
    private int show;
    private boolean willshow = true;//是否允许展示其他弹窗
    private boolean hasShowCallLiveBubble;
    private ProfileFragment profileFragment;
    private AdManager adManager;
    // 家族
    private FamilyManager familyManager;
    private FamilyUserChangeManager familyUserManager;
    private boolean isOpenShortLive;


    /**
     * @param activity
     * @param queryStr H5回调要跳转的页面字符串数据
     */
    public static void startActivity(Activity activity, String queryStr) {
        Intent intent = new Intent(activity, MainActivity2.class);
        intent.putExtra(H5Helper.H5REDIRECTION_KEY, queryStr);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        activity.startActivity(intent);
    }

    public static void startActivity(Activity activity, int status, String queryStr) {
        Intent intent = new Intent(activity, MainActivity2.class);
        intent.putExtra(H5Helper.H5REDIRECTION_KEY, queryStr);
        intent.putExtra(WebCallBackActivity.WEB_KEY, status);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        activity.startActivity(intent);
    }

    /**
     * 退出之后重新登录启动
     *
     * @param context
     */
    public static void startActivityForLogout(Context context) {
        Intent intent = new Intent(context, MainActivity2.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(BaseUserActivity.SHOW_START_STATUS_KEY, BaseUserActivity.OPEN_USER_FRAGMENT);
        intent.putExtra(BaseUserActivity.CLEAR_DATA, true);
        context.startActivity(intent);
    }

    /**
     * 打开直播界面
     *
     * @param activity
     */
    public static void startLiveActivityForUmengPush(Context activity, String queryStr) {
        Intent intent = new Intent(activity, MainActivity2.class);
        intent.putExtra(H5Helper.H5REDIRECTION_KEY, queryStr);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(intent);
    }

    /**
     * 根据推送类型打开指定界面，适用于打开的Activity无参数情况
     *
     * @param activity
     */
    public static void startActivityForUmengPush(Context activity, String notifyType) {
        Intent intent = new Intent(activity, MainActivity2.class);
        intent.putExtra(EXTRA_NOTIFY_TYPE, notifyType);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(intent);
    }

    public static void startActivityForLogout(Activity activity, int status) {
        Intent intent = new Intent(activity, MainActivity2.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.putExtra(SHOW_START_STATUS_KEY, status);
        activity.overridePendingTransition(R.anim.push_up_in, 0);
        activity.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected boolean isInterceptCreate() {
        if (!isTaskRoot()) {
            String action = getIntent().getAction();
            if (getIntent().hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(action)) {
                finish();
                return true;
            }
        }
        return false;
    }

    @Override
    protected void appLayoutIsHide(boolean hide) {
        if (dynamicsFragmentHandler != null) {
            dynamicsFragmentHandler.obtainMessage(DynamicsFragment.ACTION_4, hide).sendToTarget();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(BUNDLE_NAME_SELECT_TAB_ID, mSelectTabId);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        checkH5(intent);
    }

    private void checkH5(Intent intent) {
        String url = intent.getStringExtra(H5Helper.H5REDIRECTION_KEY);
        if (!TextUtils.isEmpty(url) && (url.indexOf("type=10", 0) > -1 || url.indexOf("type=13", 0) > -1)) {
            try {
                Uri uri = Uri.parse(url);
                String equiqId = uri.getQueryParameter("equiqId");
                int id = Integer.valueOf(equiqId);
                MarketActivity.start(MainActivity2.this, id);
                willshow = false;
                return;
            } catch (Exception e) {
            }
            MarketActivity.start(MainActivity2.this, 0);
        } else {
            // 打开回调页面
            H5Helper.startActivity(url, this);
        }
    }


    private void initListener() {
        main_rg_tab.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                tabH = main_rg_tab.getHeight() * 2;//mAppBarLayout 影响到
                if (mDiscoveryFragment != null && tabH > 0) {
                    mDiscoveryFragment.setTabH(tabH);
                    main_rg_tab.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            }
        });

        $(R.id.main_rb_action).setOnClickListener(this);
        profileSysNoticeView.setOnClickListener(this);
        setTitleBarClickListener();

        dynamcisHead.setOnItemSelectListener(new Indicator.OnItemSelectedListener() {
            @Override
            public void onItemSelected(View selectItemView, int select, int preSelect) {
                if (select == 0) {
                    dynamicsFragmentHandler.obtainMessage(DynamicsFragment.ACTION_FOCUS).sendToTarget();
                } else if (select == 1) {
                    dynamicsFragmentHandler.obtainMessage(DynamicsFragment.ACTION_SUGGEST).sendToTarget();
                }
            }
        });
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            mSelectTabId = savedInstanceState.getInt(BUNDLE_NAME_SELECT_TAB_ID);
        }

        loadShortLiveConfig();

        ispause = false;
        initWidget();
        checkUpdateCocos();
        startLoad();
        initListener();
        initTabView();
        mViewPager.setOffscreenPageLimit(mTabButtonArray.size());
        UnreadManager.getInstance().registerSocketListener(MainActivity2.this);
        initFragment();
        closeCoordBehavior();

        checkIfFromNotify();

        getLocation();
        checkWebCallBackData(getIntent());
    }


    /**
     * 符合TAb 展示建楼卡
     */
    private void showRoomHouse() {
        if (roomHouseHelper != null && ((radiodynamics.getId() == mSelectTabId || radiodiscovery.getId() == mSelectTabId) && !isCocosUpdate())) {
            bringCocosViewToFront();
            roomHouseHelper.showHouseCard();
        }
    }

    //升级变化
    private void registerSocketNotify() {
        mSocketNotify = new IMYTBASObject(false);
        mSocketNotify.stringCommand = EventHelper.EVENT_APPUPDATE;
        mSocketNotify.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(IMYTBASObject object) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mSocketNotify != null) {
                            mSocketNotify.destroy();
                        }
                        if (ispause || checkUpdateApp == null) {
                            return;
                        }
                        checkUpdateApp.showDialog(MainActivity2.this, MainActivity2.this.getSupportFragmentManager());
                    }
                });
            }
        });
        mSocketNotify.addEventListenWithTBASObject();
    }

    private void initFragment() {
        DynamicsFragment mDynamicsFragment = DynamicsFragment.newInstance();
        mDiscoveryFragment = DiscoveryFragment.newInstance();
        noticeFragment = NoticeFragment.newInstance();
        profileFragment = ProfileFragment.newInstance(0);

        if (mViewPagerAdapter == null) {
            mViewPagerAdapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager(), mDiscoveryFragment, mDynamicsFragment, noticeFragment, profileFragment);
            mViewPager.setAdapter(mViewPagerAdapter);
        }
    }

    //初始化tab按钮
    private void initTabView() {
        //特殊处理点击事件
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectTab(v.getId());
                showSomeThing();
            }
        };
        //动态添加RadioButton到数组
//        for (int id : TAB_IDS) {
        radiodiscovery = $(R.id.main_rb_discovery);
        radiodiscovery.setOnClickListener(listener);
        radiodiscovery.setRadioButtonBG(R.mipmap.faxian_2, R.mipmap.faxian_1, getResources().getString(R.string.str_tab_faxian));
        mTabButtonArray.append(radiodiscovery.getId(), radiodiscovery);

        radiodynamics = $(R.id.main_rb_dynamics);
        radiodynamics.setOnClickListener(listener);
        radiodynamics.setRadioButtonBG(R.mipmap.dongtaitubiao_2, R.mipmap.dongtaitubiao_1, getResources().getString(R.string.str_tab_dongtai));
        radiodynamics.setCheck(true);
        mTabButtonArray.append(radiodynamics.getId(), radiodynamics);

        radionotice = $(R.id.main_rb_notice);
        radionotice.setOnClickListener(listener);
        radionotice.setRadioButtonBG(R.mipmap.tongzhi_2, R.mipmap.tongzhi_1, getResources().getString(R.string.str_tab_tongzhi));
        mTabButtonArray.append(radionotice.getId(), radionotice);

        radiomine = $(R.id.main_rb_mine);
        radiomine.setOnClickListener(listener);
        radiomine.setRadioButtonBG(R.mipmap.zhuye_2, R.mipmap.zhuye_1, getResources().getString(R.string.str_tab_me));
        mTabButtonArray.append(radiomine.getId(), radiomine);
    }

    //切换tab
    private void selectTab(final int id) {
        if (mTabButtonArray != null) {
            for (int i = 0; i < mTabButtonArray.size(); i++) {
                int key = mTabButtonArray.keyAt(i);
                NavigationTabView radioButton = mTabButtonArray.get(key);
                if (key == id) {
                    // 修改CoordinatorLayout布局的依赖文件
                    if (i == 1) {
                        if (dynamicsFragmentHandler != null) {
                            dynamicsFragmentHandler.obtainMessage(DynamicsFragment.ACTION_1).sendToTarget();
                        }
                        getTitleBar().getMiddleView().removeAllViews();
                        getTitleBar().getMiddleView().addView(dynamcisHead);
                    } else {
                        getTitleBar().getMiddleView().removeAllViews();
                        ViewGroup viewGroup = (ViewGroup) dynamcisHead.getParent();
                        if (viewGroup != null) {
                            viewGroup.removeView(dynamcisHead);
                        }
                        getTitleBar().addTitleTextView();
                        if (getTitleBar() != null) {
                            getTitleBar().setTitle(getString(TAB_TITLES[i]));
                        }
                    }
                    mViewPager.setCurrentItem(i, false);
                    radioButton.setCheck(true);
                    startTabAnimtor(radioButton);
                } else {
                    radioButton.setCheck(false);
                }
            }
            setImageViewShowStatuByTabId(id);
        }
        closeCoordBehavior();
//        Fragment fragment = null;
        if (radiodynamics.getId() == id) {
//            // 点击对应的进行初始化
//            fragment = mViewPagerAdapter.getItem(1);
//            initFragmentInf(fragment);
            if (!isSameDay()) {
                PreferenceHelper.getInstance().saveToday();
            }
            MobclickAgent.onEvent(this, "dynamics_click");
            openCoordBehavior();
            if (mSelectTabId == id) {
                if (dynamicsFragmentHandler != null) {
                    if (isStart) {
                        isStart = false;
                    } else {
                        dynamicsFragmentHandler.obtainMessage(DynamicsFragment.ACTION_2).sendToTarget();
                    }
                }
            }
            showAds(TYPE_DYNAMICS);
        } else if (radiodiscovery.getId() == id) {
            MobclickAgent.onEvent(this, "find_click");
            //fragment = mViewPagerAdapter.getItem(0);
            if (mSelectTabId == id) {
                if (isStart) {
                    isStart = false;
                } else {
                    mDiscoveryFragment.scrollTop();
                }
            } else {
                MobclickAgent.onEvent(this, "find_open");
            }
            showAds(TYPE_DISCOVERY);
        } else if (radiomine.getId() == id) {
            MobclickAgent.onEvent(MainActivity2.this, "personal_click");
            showAds(TYPE_PROFILE);
            //fragment = mViewPagerAdapter.getItem(3);
        }
        // 滑动对应位置初始化界面
        /*if (fragment != null && fragment instanceof DataSetListener) {
            ((DataSetListener) fragment).loadData();
        }*/

        mSelectTabId = id;
        if (mSelectTabId == radiodiscovery.getId()) {
            iv_bgwen.setVisibility(View.VISIBLE);
        } else {
            iv_bgwen.setVisibility(View.GONE);
        }

        showAds(TYPE_OTHER);
    }

    public void showSomeThing() {
//        show = 0;
//        if (radiodynamics.getId() == mSelectTabId) {
//            show = 1;
//        } else if (radiodiscovery.getId() == mSelectTabId) {
//            show = 2;
//
//        } else if (radiomine.getId() == mSelectTabId) {
//            show = 3;
//        }
//        if (adsPersenter == null) {
//            adsPersenter = new AdsPersenter(this);
//        }
//        adsPersenter.showads(show, this);
        if (!isCocosUpdate() && roomHouseHelper != null && roomHouseHelper.getrData() == 0) {
            showRoomHouse();
        }
    }

    public int getShow() {
        return show;
    }

    @Override
    protected void onResume() {
        super.onResume();
        ispause = false;

        if (checkUpdateApp != null) {
            checkUpdateApp.showDialog(MainActivity2.this, MainActivity2.this.getSupportFragmentManager());
            willshow = checkUpdateApp.getUpdateAppFragment() == null;
        }
//        if (willshow) {
//            showSomeThing();
//        }
        willshow = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        ispause = true;
    }

    @Override
    public void onBackPressed() {

        if (IMayCocosNetManager.getInstance().getLauncherState() == 2) {
            return;
        }
        if (cocosViewShowing) {
            IMayCocos.closeMarketPannel();
            IMayCocos.closeRoomHouse();
            onCloseShopUI();
            return;
        }
        // 两秒内连按两次返回键退出程序
        long time = System.currentTimeMillis();
        if (time - mPressBackTime > 2000) {
            mPressBackTime = time;
        } else {
            IMApplication.getInstance().exit();
        }
        if (!isSameDay()) {
            PreferenceHelper.getInstance().saveToday();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSocketNotify != null) {
            mSocketNotify.destroy();
        }
        if (dynamicsFragmentHandler != null) {
            dynamicsFragmentHandler.removeCallbacksAndMessages(null);
        }
        if (familyManager != null) {
            familyManager.unregisterFamilyNotify();
        }
        if (familyUserManager != null) {
            familyUserManager.unregisterFamilyNotify();
        }

    }

    @Override
    public void onClick(View v) {
        if (checkUpdateApp != null) {
            checkUpdateApp.onClick(v);
            checkUpdateApp = null;
        }
        switch (v.getId()) {
            case R.id.main_rb_action:
                showActionButton();
                break;
            case R.id.cl_profile_system_notice:
                SystemNoticeActivity.start(this);
                MobclickAgent.onEvent(MainActivity2.this, "personal_click_notice");
                break;

        }
    }

    public void reloadData(boolean refresh) {
        if (mDiscoveryFragment != null)
            mDiscoveryFragment.reloadData(refresh);
    }

    private void showActionButton() {
        DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), MainActionButtonFragment.newInstance());
        MobclickAgent.onEvent(MainActivity2.this, "action_click");
    }

    private void setTitleBarClickListener() {
        getTitleBar().setLeftImageOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TitleBarClickHelper.leftTitleBarClick(mSelectTabId, R.id.main_rb_mine, MainActivity2.this);
                TitleBarClickHelper.leftTitleBarClick(mSelectTabId, R.id.main_rb_discovery, MainActivity2.this);
            }
        });
        getTitleBar().setRightImageOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (mSelectTabId) {
                    case R.id.main_rb_dynamics: //动态
                        if (dynamicsFragmentHandler != null) {
                            dynamicsFragmentHandler.obtainMessage(DynamicsFragment.ACTION_0).sendToTarget();
                        }
                        break;
                }
                TitleBarClickHelper.rightTitleBarClick(mSelectTabId, R.id.main_rb_mine, MainActivity2.this);
                TitleBarClickHelper.rightTitleBarClick(mSelectTabId, R.id.main_rb_discovery, MainActivity2.this);
            }
        });

    }

    //    public void changeRightIv(boolean isLinearFragmentStatus) {
//        if (isLinearFragmentStatus) {
//            getTitleBar().setRightImageResource(R.mipmap.btn_00label1);
//        } else {
//            getTitleBar().setRightImageResource(R.mipmap.btn_00label2);
//        }
//    }

    public void setDynamicsHandler(Handler handler) {
        this.dynamicsFragmentHandler = handler;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constants.REQUEST_PICK_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    if (data == null) {
                        return;
                    }
                    Bundle b = data.getExtras();
                    String imagePath = b.getString("filePath");
                    ReleaseActivity.startActivity(this, imagePath, null, null, ReleaseActivity.IMAGE, Constants.DYNAMICSFEED_REQUEST_CODE);
                }
                break;
            case Constants.REQUEST_PICK_VIDEO:
                if (resultCode == Activity.RESULT_OK) {
                    if (data == null) {
                        return;
                    }
                    Bundle b = data.getExtras();
                    String movPath = b.getString("filePath");
                    String imgPath = b.getString("imagePath");
                    ReleaseActivity.startActivity(this, imgPath, movPath, null, ReleaseActivity.MOVIE, Constants.DYNAMICSFEED_REQUEST_CODE);
                }
                break;
            default:
                if (noticeFragment != null) {
                    noticeFragment.onActivityResult(requestCode, resultCode, data);
                }
                if (profileFragment != null) {
                    profileFragment.onActivityResult(requestCode, resultCode, data);
                }
                if (mDiscoveryFragment != null) {
                    mDiscoveryFragment.onActivityResult(requestCode, resultCode, data);
                }
                break;
        }
    }

    /**
     * 设置titlebar 的左右控件的显示状态
     *
     * @param id
     */
    private void setImageViewShowStatuByTabId(int id) {
        switch (id) {
            case R.id.main_rb_dynamics:
                profileSysNoticeView.setVisibility(View.GONE);
                titleBar.setLeftViewVisibility(false);
                titleBar.setRightTextVisibility(false);
                titleBar.setRightImageResource(0);
                dynamicsFragmentHandler.obtainMessage(DynamicsFragment.ACTION_5).sendToTarget();
                //titleBar.setRightImageResource(R.mipmap.btn_00label2);
                break;
            case R.id.main_rb_discovery:
                profileSysNoticeView.setVisibility(View.GONE);
                titleBar.setLeftImageResource(R.mipmap.btn_02sousuo);
                titleBar.setRightTextVisibility(false);
                titleBar.setRightImageResource(R.mipmap.btn_02paiming);
                break;
            case R.id.main_rb_notice:
                titleBar.setLeftViewVisibility(false);
                noticeFragment.showIgnoreUnreadBtn();
                titleBar.setRightImageResource(0);
                profileSysNoticeView.setVisibility(View.GONE);
                break;
            case R.id.main_rb_mine:
                profileSysNoticeView.setVisibility(View.INVISIBLE);
                titleBar.setLeftViewVisibility(false);
                titleBar.setLeftImageVisibility(false);
                titleBar.setRightTextVisibility(false);
                titleBar.setRightImageResource(R.mipmap.btn_05t_shezhi);
                break;
        }

    }

    /**
     * 加载系统消息红点
     */
    private void loadSystemNoticeRed() {
        loadSystemNoticeRedCommand = ProtoRequestHelper.task(ProtoHttpFactory.getSystemRedPoint()).setTag(this.hashCode()).request(this);
    }

    @Override
    public void onRequestSuccess(String command, String data) {
        if (command.equals(loadSystemNoticeRedCommand)) {
            Result<String> result = JSON.parseObject(data, new TypeReference<Result<String>>() {
            }.getType());
            if (result.result == CodeSuccess) {
                iv_profile_system_notice_red.setVisibility("T".equals(result.data) ? View.VISIBLE : View.GONE);
                hasUnreadSystem = "T".equals(result.data);
                radionotice.showRedPoint(hasUnreadSystem || hasUnreadMessage || hasUnreadNotice);
                if (noticeFragment != null) {
                    noticeFragment.refreshRedPoint(hasUnreadSystem || hasUnreadMessage, 2);
                }
            }
        } else if (command.equals(loadSysParamGameShowRequest)) {
            Result<SysConfigModel> result = JSON.parseObject(data, new TypeReference<Result<SysConfigModel>>() {
            }.getType());
            if (result.data != null && IMParams.CONFIGSWITCHGAMERANKMAIN.equals(result.data.getParamKey())) {
                if ("1".equals(result.data.getValue())) {
                    IMParams.isShowRankingGame = true;
                } else if ("0".equals(result.data.getValue())) {
                    IMParams.isShowRankingGame = false;
                }
            } else if (result.data != null && CONFIG_SWITCH_RECHARGE_TIP.equals(result.data.getParamKey())) {

            }
        }
    }

    @Override
    public void onRequestError(String command, int code, String message) {

    }

    List<UnreadModel> unreadModelList = new ArrayList<>();

    //红点显示回调
    @Override
    public void onStatusChange(final UnreadModel unreadModel) {
        if (!isMain) {
            unreadModelList.add(unreadModel);
            return;
        }
        if (unreadModel == null) return;
        switch (unreadModel.getWarnType()) {
            case UnreadManager.TYPE_UNREAD_SYSTEM_PROFILE:
                ThreadManager.post(ThreadManager.THREAD_UI, new Runnable() {
                    @Override
                    public void run() {
                        iv_profile_system_notice_red.setVisibility(unreadModel.haveUnread() ? View.VISIBLE : View.GONE);
                        hasUnreadSystem = unreadModel.haveUnread();
                        radionotice.showRedPoint(hasUnreadSystem || hasUnreadMessage || hasUnreadNotice);
                        if (noticeFragment != null) {
                            noticeFragment.refreshRedPoint(hasUnreadSystem || hasUnreadMessage, 2);
                        }
                    }
                });
                break;
            case UnreadManager.TYPE_UNREAD_SYSTEM:
                if (!TextUtils.isEmpty(unreadModel.getData())) {
                    if (noticeFragment != null) {
                        noticeFragment.refreshSystemNotify();
                    }
                }
                break;
            case MessageManager.NewWarnType.IMBubbleLiveType: // 直播间通知
                onLiveNotify(unreadModel.getValue());
                break;
            case IMBubbleCommentType:
            case IMBubbleMindType:
            case IMBubbleGiftType:
            case IMBubbleRePostType:
            case IMBubblePraiseType:
            case IMBubbleFollowType:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (unreadModel.haveUnread()) {
                            if (isMain) {
                                NoticeBubbleManager.getInstance().showBubbleDialog(MainActivity2.this, unreadModel, radionotice);
                            }
                        } else {
                            NoticeBubbleManager.getInstance().clearMineNoticeUnreadData();
                        }
                        hasUnreadNotice = unreadModel.haveUnread();
                        radionotice.showRedPoint(hasUnreadNotice || hasUnreadMessage || hasUnreadSystem);
                        if (noticeFragment != null) {
                            noticeFragment.refreshRedPoint(hasUnreadNotice, 0);
                        }

                    }
                });
                break;
            case TYPE_UNREAD_MESSAGE:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (unreadModel.haveUnread()) {
                            unreadModel.setValue(noticeFragment.getRecentUnreadCount());
                            if (isMain) {
                                NoticeBubbleManager.getInstance().showBubbleDialog(MainActivity2.this, unreadModel, radionotice);
                            }
                        } else {
                            NoticeBubbleManager.getInstance().clearRecentMessageNoticeUnreadData();

                        }
                        hasUnreadMessage = unreadModel.haveUnread();
                        radionotice.showRedPoint(hasUnreadMessage || hasUnreadSystem || hasUnreadNotice);
                        if (noticeFragment != null) {
                            noticeFragment.refreshRedPoint(hasUnreadSystem || hasUnreadMessage, 2);
                        }
                    }
                });
                break;
            case TYPE_UNREAD_FAMILY_MESSAGE:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hasUnreadMessage = unreadModel.haveUnread();
                        radionotice.showRedPoint(hasUnreadMessage || hasUnreadSystem || hasUnreadNotice);
                        if (noticeFragment != null) {
                            noticeFragment.refreshRedPoint(hasUnreadSystem || hasUnreadMessage, 2);
                        }
                    }
                });
                break;
            case TYPE_UNREAD_CALL_LIVE_PROFILE:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (radiomine != null) {
                            radiomine.showRedPoint(unreadModel.haveUnread());
                        }
                        if (profileFragment != null) {
                            profileFragment.setCallLiveRedVisible(unreadModel.haveUnread());
                        }

                    }
                });
                break;
        }


    }

    @Override
    public void onLiveNotify(final int size) {
        ThreadManager.post(ThreadManager.THREAD_UI, new Runnable() {
            @Override
            public void run() {
                if (isMain) {
                    radiodynamics.showRedPoint(true);
                    NoticeBubbleManager.getInstance().showLiveBubbleDialog(MainActivity2.this, radiodynamics, size);
                }
            }
        });
    }

    public void hideRedPoint() {
        radiodynamics.showRedPoint(false);
    }


    @Override
    public void onCloseShopUI() {
        revertCocosView();
    }

    /**
     * 展示商城
     */
    public void showMarketPannel(final Integer mountId) {
        bringCocosViewToFront();
        if (onCocosUpdateListener != null) {//防止建楼卡
            IMayCocos.getInstance().removeOnCocosUpdateListener(onCocosUpdateListener);
        }
        onCocosUpdateListener = new IMayCocos.OnCocosUpdateListener() {
            @Override
            public void onCocosAllowAction(int state) {
                if (state == 3) {
                    IMayCocos.showMarketPanel(mountId);
                    MobclickAgent.onEvent(MainActivity2.this, "mall_open");
                }
            }
        };
        IMayCocos.getInstance().addOnCocosUpdateListener(onCocosUpdateListener);
    }

    @Override
    public void onCocosRechargeClick() {
        RechargeActivity.start(this);
    }

    public void loadDiscoveryData(LoadFragment fragment, int refresh) {
        mDiscoveryFragment.reloadData(fragment, refresh);
    }

    /**
     * 是否展示广告后的 建楼卡逻辑
     */
    @Override
    public void onShowAds() {
        showBuildCardAfterAd();
    }

    private void showBuildCardAfterAd() {
        if (IMayCocos.getInstance().getAppUpdateModel() != null || isCocosUpdate()) {
            return;
        }
        if ((radiodynamics.getId() == mSelectTabId || radiodiscovery.getId() == mSelectTabId)) {//不展示广告时候
            final boolean houseshow = AppUtil.showRoomHouseUi();
            if (!houseshow) {
                return;
            }
            if (roomHouseHelper == null) {
                roomHouseHelper = new RoomHouseHelper();
                roomHouseHelper.getHouseCard(new RoomHouseHelper.OnRoomHouseListener() {
                    @Override
                    public void onShowUI(final int rData, final int userLv) {
                        roomHouseHelper.setData(rData, userLv);
                        if (cocosViewShowing) {//预防商城打开
                            return;
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (!isCocosUpdate() && roomHouseHelper.getrData() == 0) {
                                    showRoomHouse();
                                }
//
                            }
                        });

                    }

                    @Override
                    public void onClose(final int receiveStatus) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (receiveStatus == 0) {
                                    IMayCocos.closeRoomHouse();
                                    onCloseShopUI();
                                }
                                roomHouseHelper = null;
                            }
                        });
                    }

                    @Override
                    public void onOpenH5(String url) {
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.append(url);
                        if (url.indexOf("?", 0) > -1) {
                            stringBuilder.append("&");
                        } else {
                            stringBuilder.append("?");
                        }
                        stringBuilder.append("uid=");
                        stringBuilder.append(AccountManager.getInstance().getUid());
                        if (AccountManager.getInstance().getToken() != null) {
                            stringBuilder.append("&accessToken=");
                            stringBuilder.append(AccountManager.getInstance().getToken().accessCode);
                        }
                        WebViewActivity.startActivity(MainActivity2.this, url);
                        roomHouseHelper = null;
                    }
                });

            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (roomHouseHelper != null && roomHouseHelper.getrData() == 0 && onCocosUpdateListener == null && !cocosViewShowing) {
                            showRoomHouse();
                        }
                    }
                });
            }
        }
    }

    /**
     * 排行榜的
     */
    private void loadSysParamGameShow() {
        loadSysParamGameShowRequest = ProtoRequestHelper.task(ProtoHttpFactory.getRankingGameStatus()).setTag(this.hashCode()).request(this);
    }

    /**
     * 登录之后进行请求对应数据或者执行对应的UI逻辑模块
     */
    @Override
    public void loadData() {
        //initPermission();

        ((IMApplication) getApplication()).userLoseNotify();

        if (!StringUtil.isEmpty(getIntent().getStringExtra(EXTRA_NOTIFY_TYPE))) {
            mSelectTabId = radiomine.getId();
        } else {
            mSelectTabId = radiodiscovery.getId();
        }
        isStart = true;
        mDiscoveryFragment.setTabH(tabH);
        // 打开回调页面
        mViewPager.post(new Runnable() {
            @Override
            public void run() {
                familyManager = FamilyManager.Builder.create(MainActivity2.this).build();
                familyUserManager = FamilyUserChangeManager.Builder.create(MainActivity2.this).build();
                loadSystemNoticeRed();
                loadSysParamGameShow();
                DynamicsNotifyManager.getInstance().registerDynamicNotifyListener(dynamicsFragmentHandler);
                IMayCocosNetManager.getInstance().setOnCocosShopListener(MainActivity2.this);

                // 加载数据
                DataSetManager.loadData();

                selectTab(mSelectTabId);
            }
        });


        if (!isCocosUpdate()) {
            boolean hasout = H5Helper.startActivity(h5data, this);
            h5data = "";
            if (!hasout) {//互斥
                checkUpdateApp = new CheckUpdateApp();
                if (!checkUpdateApp.showDialog(MainActivity2.this, getSupportFragmentManager())
                        && !ActivityHelper.getInstance().isBackground()) {
                    if (isOpenShortLive) {
                        RoomLiveShortActivity.startActivity(MainActivity2.this, true);
                    }
                    showAdFirst();
                    registerSocketNotify();
                } else {
                    willshow = false;
                }
            }
        } else {
            bringCocosViewToFront();
        }

        // 重新加载未读的通知
        if (unreadModelList != null && !unreadModelList.isEmpty()) {
            for (final UnreadModel unreadModel : unreadModelList) {
                ThreadManager.postDelayed(ThreadManager.THREAD_BACKGROUND, new Runnable() {
                    @Override
                    public void run() {
                        onStatusChange(unreadModel);
                    }
                }, 500);
            }
            unreadModelList.clear();
        }
    }

    /***
     * 进行loadData信息，为了防止卡死，最好操作对应的界面再初始化信息
     * @param fragment
     */
//    private void initFragmentInf(Fragment fragment) {
//        if (fragment != null && fragment instanceof DataSetListener) {
//            ((DataSetListener) fragment).loadData();
//        }
//    }

    /**
     * cocos更新完成
     */
    @Override
    public void cocosUpdateSuccess() {
        if (isCocosViewShowing()) {
            revertCocosView();
            showAdFirst();
            if (isOpenShortLive) {
                RoomLiveShortActivity.startActivity(MainActivity2.this, true);
            }
        }
    }

    private void showAdFirst() {
        if (mSelectTabId == radiomine.getId()) {
            showAds(TYPE_PROFILE);
        } else if (mSelectTabId == radiodiscovery.getId()) {
            showAds(TYPE_DISCOVERY);
        }
        showAds(TYPE_OTHER);
    }

    /**
     * 暴露显示召唤直播方法给ProfileFragment 调用
     */
    public void showCallLiveBubble(int count) {
        if (radiomine != null) {
            radiomine.showRedPoint(count > 0);
        }
        if (isMain && !hasShowCallLiveBubble && count > 0) {
            NoticeBubbleManager.getInstance().showCallLiveBubbleDialog(MainActivity2.this, radiomine, count);
            hasShowCallLiveBubble = true;
        }
    }

    /**
     * 如果是点击召唤直播进来的, 要跳转
     */
    private void checkIfFromNotify() {
        String notifyType = getIntent().getStringExtra(EXTRA_NOTIFY_TYPE);
        if (ENTER_USER_CALLLIVE.equals(notifyType)) {
            UserInfoModel model = UserInfoCache.getUserInfo();
            mSelectTabId = radiomine.getId();
            selectTab(mSelectTabId);
            if (model != null) {
                HoldCallLiveActivity.startActivity(this, model.getUser().getUid(), model.getUser().getNick());
            }
        }
    }

    private boolean isSameDay() {
        return TimeUtil.getToday().equals(PreferenceHelper.getInstance().getSaveDay());
    }

    private AdManager getAdManager() {
        if (adManager == null) {
            adManager = AdManager.getInstance();
            adManager.setOnShowAdListener(this);
            if (!isSameDay()) {
                PreferenceHelper.getInstance().saveShowAdId("");
            }
        }
        return adManager;
    }

    private void showAds(int type) {
        boolean updateDialogShowing = false;
        if (checkUpdateApp != null) {
            updateDialogShowing = checkUpdateApp.updateDialogShowing;
        }
        if (!isCocosUpdate() && !updateDialogShowing) {
            getAdManager().showTabAd(getSupportFragmentManager(), type);
        }
    }

    /**
     * ==============家族回调==============
     */
    @Override
    public void familyCreate() {
        FamilyAccountManager.getInstance().loadFamilyUserInfo(true);
        if (noticeFragment != null) {
            noticeFragment.refreshSystemNotify();
        }
    }

    @Override
    public void familyLvUpgrade() {
        FamilyAccountManager.getInstance().loadFamilyUserInfo(false);
        if (noticeFragment != null) {
            noticeFragment.refreshSystemNotify();
        }
    }

    @Override
    public void familyUserApply(FamilyApplyNotify familyApplyNotify) {
        if (familyApplyNotify.type == FamilyParams.FAMILYUSERAPPLYNOTIFY_JOIN_TYPE) {
            FamilyAccountManager.getInstance().loadFamilyUserInfo(true);
        }
        if (noticeFragment != null) {
            noticeFragment.refreshSystemNotify();
        }
    }

    @Override
    public void familyEdit() {
        FamilyAccountManager.getInstance().loadFamilyUserInfo(false);
        if (noticeFragment != null) {
            noticeFragment.refreshSystemNotify();
        }
    }

    @Override
    public void familyBeLocked() {
        FamilyAccountManager.getInstance().loadFamilyUserInfo(false);
        if (noticeFragment != null) {
            noticeFragment.refreshSystemNotify();
        }
    }

    @Override
    public void familyUnLocked() {
        FamilyAccountManager.getInstance().loadFamilyUserInfo(false);
        if (noticeFragment != null) {
            noticeFragment.refreshSystemNotify();
        }
    }

    @Override
    public void elderChange() {
        FamilyAccountManager.getInstance().loadFamilyUserInfo(false);
        if (noticeFragment != null) {
            noticeFragment.refreshSystemNotify();
        }
    }

    @Override
    public void userRefresh() {
        FamilyAccountManager.getInstance().loadFamilyUserInfo(false);
        if (noticeFragment != null) {
            noticeFragment.refreshSystemNotify();
        }
    }

    public void showFirstRechargeButton(String buttonUrl,final String imageUrl) {
        FirstRechargeManager.getInstance().loadWebp(buttonUrl,sdv_first_rechage);
        FirstRechargeManager.getInstance().registerRechargeNotify();
        sdv_first_rechage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AdsModel adsModel = new AdsModel();
                adsModel.setPhoto(imageUrl);
                adsModel.setJumpContent("imay://com.imay.live/openwith?type=4");
                ShowAdsFragment fragment = ShowAdsFragment.newInstance(adsModel);
                DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), fragment);

            }
        });

    }

    // 是否打开超胆播
    private void loadShortLiveConfig(){
        ProtoRequestHelper.task(ProtoHttpFactory.getSysparam("ConfigSwitchShortLivePage")).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                Result<SysparamModel> result = JSON.parseObject(data,new TypeReference<Result<SysparamModel>>(){}.getType());
                ImayLogUtil.log("ConfigSwitchShortLivePage"+data);
                if (result.result==CodeSuccess){
                    isOpenShortLive = result.data.getValue()==1;
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {

            }
        });


    }



}